package com.bigzhao.jianrmagicbox.checker;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigzhao.jianrmagicbox.aidl.IMagicBoxBinder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;


public class MainActivity extends Activity {

    private EditText et;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_main);
            et = (EditText) findViewById(R.id.editText);
            tv = (TextView) findViewById(R.id.textView);

            action(R.id.button, new Action() {
                @Override
                public Object action() throws RemoteException {
                    return action("selfcheck", "tree");
                }
            });

            action(R.id.button2, new Action() {
                @Override
                public Object action() throws RemoteException {
                    return action("selfcheck", "checkModule");
                }
            });

            action(R.id.button3, new Action() {
                @Override
                public Object action() throws RemoteException {
                    String path = action("getFilePath", et.getText().toString()) + "";
                    return action("selfcheck", "checkChildren", path);
                }
            });

            action(R.id.button4, new Action() {
                @Override
                public Object action() throws RemoteException {
                    return versionString(b.getVersion());
                }
            });

            action(R.id.button5, new Action() {
                @Override
                public Object action() throws RemoteException {
                    action("delete", "files:MagicBox/module");
                    return b.getVersion();
                }
            });

            action(R.id.button6, new Action() {
                @Override
                public Object action() throws RemoteException {
                    return action("getUserInfo");
                }
            });

            action(R.id.button7, new Action() {
                @Override
                public Object action() throws RemoteException {
                    try {
                        File f = getExternalFilesDir("MagicBox");
                        f = new File(f, "module");

                        StringBuilder result = new StringBuilder();
                        File classDex = new File(f, "classes.dex");
                        if (classDex.exists()) {
                            action("copy", classDex.getCanonicalPath(), "files:MagicBox/module/classes.dex");
                            result.append("classes.dex").append("复制成功\r\n");
                        }else{
                            result.append(classDex.getAbsolutePath()+ " 不存在\r\n");
                        }

                        File so = new File(f, "libMagicBox.so");
                        if (so.exists()) {
                            action("copy", so.getCanonicalPath(), "files:MagicBox/module/libMagicBox.so");
                            result.append("libMagicBox.so").append("复制成功\r\n");
                        }else{
                            result.append(so.getAbsolutePath()+ " 不存在\r\n");
                        }
                        return result.toString();
                    }catch (Throwable e){
                        e.printStackTrace();
                        return exceptionToString(e);
                    }
                }
            });

            action(R.id.button8, new Action() {
                @Override
                public Object action() throws RemoteException {
                    String s= action("getUserDetail")+"";
                    s=s.length()+": "+s;
                    return s;
                }
            });

            action(R.id.button9, new Action() {
                @Override
                public Object action() throws RemoteException {
                    try {
                        Runtime r = Runtime.getRuntime();
                        r.exec("su");
                        r.exec("rm -r \"/data/data/com.bigzhao.jianrmagicbox/files/MagicBox\"");
                        return "success";
                    }catch (Throwable e){
                        e.printStackTrace();
                        return e;
                    }
                }
            });

            action(R.id.button10, new Action() {
                @Override
                public Object action() throws RemoteException {
                    return action("getLastLog", et.getText().toString());
                }
            });

            tv.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    ClipboardManager myClipboard;
                    myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    ClipData myClip;
                    String text = tv.getText().toString();
                    myClip = ClipData.newPlainText("text", text);
                    myClipboard.setPrimaryClip(myClip);
                    Toast.makeText(MainActivity.this, "已复制到剪贴板", Toast.LENGTH_SHORT).show();

                    return true;
                }
            });

        }catch (Throwable e){
            TextView tv=new TextView(this);
            tv.setText(e+"");
            setContentView(tv);
        }
    }

    private static abstract class Action{
        public IMagicBoxBinder b;
        public abstract Object action() throws RemoteException;
        public Object action(IMagicBoxBinder b) throws RemoteException {
            this.b=b;
            return action();
        }
        public Object action(String cmd,String...args) throws RemoteException {
            return b.action_remote(cmd,args);
        }
    }
    public void action(int id, final Action action){
        findViewById(id).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                action(action);
            }
        });
    }

    public void action(final Action action){
        Intent intent=new Intent("com.bigzhao.jianrmagicbox.action.SERVICE");
        intent.setPackage("com.bigzhao.jianrmagicbox");
        startService(intent);
        if (!bindService(intent, new ServiceConnection() {
            private boolean bound=false;
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                if (bound) return;
                try{
                    bound=true;
                    IMagicBoxBinder binder=IMagicBoxBinder.Stub.asInterface(iBinder);
                    Object ret=action.action(binder);
                    tv.setText(String.valueOf(ret));
                }catch (Throwable e){
                    tv.setText(exceptionToString(e));
                }
            }
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                tv.setText("连接失败，请确认已安装魔改专用包并且已启动。\n错误组件:"+componentName);
            }
        },BIND_AUTO_CREATE)){
            tv.setText("连接失败，请确认已安装魔改专用包并且已启动。");
        };
    }

    public static String versionString(int version){
        return String.format("%d.%d.%d.%d",
                version/(1<<24)%256,
                version/(1<<16)%256,
                version/(1<<8)%256,
                version%256
        );
    }

    public static String exceptionToString(Throwable t){
        ByteArrayOutputStream os=new ByteArrayOutputStream();
        PrintStream ps=new PrintStream(os);
        ps.println(t.getMessage());
        while(t!=null){
            t.printStackTrace(ps);
            if (t.getCause()==t) {
                ps.println("...");
                break;
            }
            t=t.getCause();
        }
        String s=os.toString();
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(ps);
        return s;
    }
}
